#include "head.h"

mqd_t msqid_server;
mqd_t msqid_client;

void sigint(int signo) {
	if (mq_close(msqid_server) == -1 || mq_close(msqid_client) == -1) {
		perror("mqclose server");
		exit(1);
	} else {
		printf("Zamykanie kolejki\n");
		return;
	}
}

void readqueue() {
	struct message msg;
	while(1) {
		if(mq_receive(msqid_client, (char *)&msg, sizeof(struct message), NULL) != -1) {
			printf("%s", msg.msg);
		}
	}
}

int main(int argc, char ** argv) {
	if (argc != 4) {
		printf("Niepoprawne wywolanie. Wywolanie: ./client.o <path> <path> <name>\n");
		return 1;
	}
	if (signal(SIGINT, sigint) == SIG_ERR) {
		perror("signal client");
		return -1;
	}
	char * name_srv = (char *)malloc(sizeof(char)*128), * name_cl = (char *)malloc(sizeof(char)*128);
	sprintf(name_srv, "/%s", argv[1]);
	sprintf(name_cl, "/%s", argv[2]);
	name_cl[strlen(name_cl)+1] = name_srv[strlen(name_srv)+1] = '\0';
	if ((msqid_server = mq_open(name_srv, O_WRONLY)) == -1) {
		perror("mq_open server");
		return -2;
	}
	struct mq_attr attr;
	attr.mq_flags = 0;
	attr.mq_maxmsg = 10;
	attr.mq_msgsize = sizeof(struct message);
	if ((msqid_client = mq_open(name_cl, O_RDONLY | O_CREAT, 0666, &attr)) == -1) {
		perror("mq_open client");
		return 6;
	}
	//struct server_mess srv_mess;
	struct message cl_mess;
	cl_mess.type = 1;
	sprintf(cl_mess.name, "%s", argv[3]);
	sprintf(cl_mess.msg, "%s", name_cl);
	if (mq_send(msqid_server, (char *)&cl_mess, sizeof(struct message), 0) == -1) {
		perror("mq_send");
		return -4;
	}
	pid_t pid;
	if ((pid = fork()) < 0) {
		perror("fork");
	} else if (pid == 0) {
		readqueue();
	} else {
		while (1) {
			char * buffer = (char *)malloc(sizeof(char)*1024);
			fgets(buffer, sizeof(char)*1024, stdin);
			time_t times = time(NULL);
			struct tm * h_time = localtime(&times);
			sprintf(cl_mess.msg, "%d:%d:%d %s:%s", h_time->tm_hour, h_time->tm_min, h_time->tm_sec, argv[3], buffer);
			cl_mess.msg[strlen(cl_mess.msg)+1] = '\0';
			strncpy(cl_mess.name, name_cl, sizeof(char)*strlen(name_cl));
			cl_mess.type = 2;
			if (mq_send(msqid_server, (char *)&cl_mess, sizeof(struct message), 0) == -1) {
				perror("mq_send client");
				return -3;
			}
			free(buffer);
		}
	}
	return 0;
}
